import {Component, computed, effect, inject, OnInit, signal} from '@angular/core';
import {CommonModule} from '@angular/common';
import {AppStoreService} from "./app-store.service";

@Component({
  selector: 'app-signal',
  standalone: true,
  imports: [CommonModule],
  templateUrl: './signal.component.html',
  styleUrl: './signal.component.css'
})

export class SignalComponent implements OnInit {

  num = 1

  count = signal(0)
  showCount = signal(false);

  appStore = inject(AppStoreService)

  constructor() {
    // Register a new effect.
    effect(() => {
      console.log(`The count is: ${this.count()}`);
    });
  }

  ngOnInit(): void {
    console.log('The count is: ' + this.count());

    this.count.set(10)
  }

  // 属性计算量
  //参与计算的信号量其中一个改变，就重新计算，否则读上次计算的缓存结果
  //计算量只读
  butter = computed(() => this.count() * 0.1);
  sugar = computed(() => this.count() * 0.05);
  flour = computed(() => this.count() * 0.2);

  conditionalCount = computed(() => {
    if (this.showCount()) {
      return `The count is ${this.count()}.`;
    } else {
      return 'Nothing to see here!';
    }
  })

  update(event: Event) {
    const input = event.target as HTMLInputElement;
    this.count.set(parseInt(input.value));
  }

  updateCount() {
    this.count.update(value => value + 1)
  }

  updateShowCount() {
    this.showCount.update(value => !value)
  }

}
